<template>
  <div :id="id" :class="className" :style="{ height, width }"/>
</template>

<script setup lang="ts">
import {ref, onMounted} from "vue";
import * as echarts from 'echarts';

const props = defineProps({
  id: {
    type: String,
    default: "pieEcharts",
  },
  className: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "100%",
    required: true,
  },
  height: {
    type: String,
    default: "220px",
    required: true,
  },
});


const chart: Ref<echarts.ECharts | null> = ref(null);

/** 设置图表  */
const setChartOptions = (data: any) => {
  if (!chart.value) {
    return;
  }
  const options = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 0,
      bottom: 30,
      textStyle: {
        color: "#ffffff"
      },
      data: data.legendData
    },
    series: [
      {
        name: '分类占比',
        type: 'pie',
        radius: '55%',
        center: ['40%', '50%'],
        itemStyle: {
          borderRadius: 5
        },
        data: data.seriesData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  chart.value.setOption(options);
};

const loadData = () => {
  setChartOptions({
    legendData: ["纸品家清", "礼盒专区", "酒水饮料", "休闲零食", "计生用品", "玩具系列", "数码电器", "办公文具", "日用百货", "纺织用品", "酒水品类", "个人护理"],
    seriesData: [
      {value: 11, name: "纸品家清"},
      {value: 9, name: "礼盒专区"},
      {value: 8, name: "酒水饮料"},
      {value: 18, name: "休闲零食"},
      {value: 3, name: "计生用品"},
      {value: 7, name: "玩具系列"},
      {value: 0, name: "数码电器"},
      {value: 3, name: "办公文具"},
      {value: 9, name: "日用百货"},
      {value: 2, name: "纺织用品"},
      {value: 13, name: "酒水品类"},
      {value: 8, name: "个人护理"}
    ]
  });
}

// 窗口大小变化时，重置图表大小
const handleResize = () => {
  setTimeout(() => {
    if (chart.value) {
      chart.value.resize();
    }
  }, 100);
};

onMounted(() => {
  chart.value = markRaw(echarts.init(document.getElementById(props.id) as HTMLDivElement));
  loadData();
  window.addEventListener("resize", handleResize);
})
</script>

<style scoped>

</style>
